Java 2

클래스의 정의와 인스턴스 생성
객체지향 프로그래밍(Object-Oriented Programming, OOP)
Java, C++, C# 에서 사용됨
클래스는 필드(변수 저의)와 메소드(함수)로 구성되어 있다.
인스턴스는 클래스로 생성된 객체를 말한다.(인스턴스==객체)
Car myCar1=new Car(); // myCar1은 Car 클래스 인스턴스
// Car.java
public class Car{
String color; // 변수
int speed=0; // 변수
int getSpeed(){ // 메서드
return speed;
}
void upSpeed(int value){ // 메서드
if(speed+value>=200)speed=200;
else speed=speed+value;
}
void downSpeed(int value){ // 메서드
if(speed-value<=0)speed=0;
else speed=speed-value;
}
String getColor(){ // 메서드
return color;
}
}
인스턴스 생성
// exam07.java
public class exam07{
public static void main(String args[]){
Car myCar1=new Car(); // 인스턴스 생성
myCar1.color="빨강";
myCar1.speed=0;
Car myCar2=new Car(); // 인스턴스 생성
myCar2.color="파랑";
myCar2.speed=0;
myCar1.upSpeed(50);
System.out.println("자동차1의 색상은 "+myCar1.getColor()+"이며, 속도는 "+myCar1.getSpeed()+" km입니다.");
myCar1.downSpeed(2);
// ...
myCar2.upSpeed(250);
// ...
}
}
생성자
public class Car{
String color;
int speed;
Car(String color, int speed){ // 생성자
this.color=color;
this.speed=speed;
}
}
메소드 오버로딩(여러 개의 생성자 정의 인자별로)
public class Car{
String color;
int speed;
Car(String color, int speed){
this.color=color;
this.speed=speed;
}
Car(int speed){ // 생성자 오버로딩 생성
this.speed=speed;
}
Car(){} // 생성자 오버로딩 생성
// ...
}
정적 필드(static field) & 정적 메서드(static method)
public class Car{
String color;
int speed;
static int carCount=0; // carCount는 정적 변수로 인스턴스와 클래스로도 호출가능
final static int MAXSPEED=200;
final static int MINSPEED=0;
static int currentCarCount(){
return carCount;
}
Car(String color, int speed){
this.color=color;
this.speed=speed;
carCount++;
}
// ...
}
클래스 상속과 메소드 오버라이딩
클래스 상속을 통해서 부모 클래스(Super class)의 필드와 메소드를 물려받고,
추가적인 메소드와 변수들을 정의할 수 있다.(Sub class)
// Automobile.java
public class Automobile extends Cars{ // Cars 클래스를 상속(extends)
int seatNum; // 추가적인 변수 정의
int getSeatNum(){ // 추가적인 메소드 정의
return seatNum;
}
void upSpeed(int value){ // Cars의 메소드 오버라이딩
if(speed+value>=300) speed=300; // super 클래스의 변수 사용(speed)
else speed=speed+(int)value;
}
}
//exam.java
public class exam{
public static main(String args[]){
Automobile auto=new Automobile();
auto.upSpeed(250);
System.out.println("승용차의 속도는 "+auto.getSpeed()+" km입니다.");
// getSpeed()는 Automobile의 super 클래스 메소드
}
}
추상 클래스 & 추상 메서드(abstract)
추상 클래스는 인스턴스를 만들 수 없으며, 상속만 가능하다.
추상 메서드 또한 내용을 가지고 있지 않으며, 필요할 때 직접 오버라이딩해서 사용한다.
// Animal.java
abstract class Animal{
String name;
abstract void move();
}
// Tiger.java
class Tiger extends Animal{
int age;
void move(){
System.out.println("네발로 이동한다.");
}
}
다형성(polymorphism)
다형성은 하나의 객체가 여러 가지 타입을 가질 수 있는 것을 의미한다.

자바에서는 부모 클래스 타입의 참조 변수로 자식 클래스 타입의 인스턴스를 참조할 수 있도록 구현하고 있다.
(자식 클래스 타입의 참조 변수에 부모 클래스 타입의 인스턴스 참조는 불가능)
//exam11.java
public class exam11{
public static void void main(String args[]){
Animal animal; // 다형성(추상클래스를 통해서 변수를 생성)
animal=new Tiger();
animal.move();
anmal=new Eagle();
animal.move();
}
}
인터페이스(Interface)
class 라는 키워드 대신에 interface라는 키워드로 정의해 준다.
추상 메서드로만 구성되어 있다.

interface는 implements를 통해서 class에서 정의한다.
//exam12.java
interface iAnimal{
abstract void eat();
}
public class exam12{
public static void main(String args[]){
iCat cat=new iCat();
cat.eat();
iTiger tiger=new iTiger();
tiger.move();
tiger.eat();
}
}
static class iCat implements iAnimal{ // implements를 통해서 인터페이스 구현
public void eat(){
System.out.println("생선을 좋아한다.");
}
}
static class iTiger extends Animal implements iAnimal{
// Animal 클래스 상속, iAnimal 인터페이스 구현
void move(){
System.out.println("네발로 이동한다.");
}
public void eat(){
System.out.println("멧돼지를 잡아먹는다.");
}
}
추상(abstract) 클래스를 이용해서 인스턴스를 생성할 수 없지만,
인터페이스(interface) 클래스를 이용해서 인스턴스를 생성할 수 있음

인터페이스를 이용해서 만들 인스턴스를 익명 내부 클래스라고 함
익명 내부 클래스
인터페이스를 통해서 인스턴스를 생성
인터페이스를 생성과 동시에 내부 메서드를 정의
interface clickListener{
public void print();
}
public class exam13{
public static void main(String args[]){
clickListener listener=(new clickListener(){
public void print(){
System.out.println("클릭 리스너입니다.");
}
}); // 인스턴스를 생성하면서, 인터페이스 함수를 정의
listener.print();
}
}
데이터 형식 변환, 문자열 비교
데이터 형식 변환
int a=Integer.parseInt("100"); // 문자열 -> 정수형
double b=Double.parseDouble("100.123"); // 문자열 -> 실수형(double)
문자열 비교
String str="안녕하세요";
if(str.equals((String)"안녕하세요")){
// 문자열 같으면 수행
}
날짜형식
Date now=new Date();
SimpleDateFormat sFormat;
sFormat=new SimpleDateFormat("yyyyMMdd");
System.out.println(sFormat.format(now));
sFormat=new SimpleDateFormat("HH:mm:ss");
System.out.println(sFormat.format(now));